import axios from 'axios'
import { AI_CHAT_API_BASE_URL } from '../utils/constants'
import { getToken } from '@/utils/auth'

// 创建专门用于开发计划的 axios 实例（使用 AI Chat API 地址，与知识库一致）
const devPlanApi = axios.create({
  baseURL: AI_CHAT_API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器：添加 token
devPlanApi.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器：处理响应和错误
devPlanApi.interceptors.response.use(
  (res) => {
    return res.data
  },
  (error) => {
    console.error('开发计划 API 错误:', error)
    // 处理 FastAPI 返回的错误格式 {detail: "错误信息"}
    if (error.response?.data?.detail) {
      return Promise.reject(new Error(error.response.data.detail))
    }
    return Promise.reject(error)
  }
)

const BASE = '/api/development-plan'

export const getDevelopmentPlan = () => {
  return devPlanApi.get(BASE)
}

export const createPlanStage = (payload) => {
  return devPlanApi.post(`${BASE}/stages`, payload)
}

export const updatePlanStage = (id, payload) => {
  return devPlanApi.put(`${BASE}/stages/${id}`, payload)
}

export const deletePlanStage = (id) => {
  return devPlanApi.delete(`${BASE}/stages/${id}`)
}

export const createPlanTask = (payload) => {
  return devPlanApi.post(`${BASE}/tasks`, payload)
}

export const updatePlanTask = (id, payload) => {
  return devPlanApi.put(`${BASE}/tasks/${id}`, payload)
}

export const deletePlanTask = (id) => {
  return devPlanApi.delete(`${BASE}/tasks/${id}`)
}

export const createTaskStage = (taskId, payload) => {
  return devPlanApi.post(`${BASE}/tasks/${taskId}/stages`, payload)
}

export const updateTaskStage = (taskId, stageId, payload) => {
  return devPlanApi.put(`${BASE}/tasks/${taskId}/stages/${stageId}`, payload)
}

export const deleteTaskStage = (taskId, stageId) => {
  return devPlanApi.delete(`${BASE}/tasks/${taskId}/stages/${stageId}`)
}

export const archiveTask = (taskId) => {
  return devPlanApi.post(`${BASE}/tasks/${taskId}/archive`)
}

export const getArchivedTasks = () => {
  return devPlanApi.get(`${BASE}/archived`)
}

export const unarchiveTask = (taskId) => {
  return devPlanApi.post(`${BASE}/tasks/${taskId}/unarchive`)
}

export default {
  getDevelopmentPlan,
  createPlanTask,
  updatePlanTask,
  deletePlanTask,
  createTaskStage,
  updateTaskStage,
  deleteTaskStage,
  archiveTask,
  getArchivedTasks,
  unarchiveTask
}

